exports.__esModule = true;

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

exports.default = class extends think.Service {
    constructor() {
        super();
        this.oaNotifyModel = this.db['oa_notify'];
        this.oaNotifyRecordModel = this.db['oa_notify_record'];
        this.userModel = this.db['sys_user'];
        this.orgModel = this.db['sys_org'];
        this.attachmentModel = this.db['sys_attachment'];
        this.eventModel = this.db['cms_event'];
        this.areaCodeModel = this.db['cms_area'];
        this.weChatUserModel = this.db['wechat_user'];

        this.typeModel = this.db['sys_type'];
        this.type_group_model = this.db['sys_type_group'];
        this.pushServerUrl = think.config('pushServerUrl');
    }

    //查询公告列表
    oaNotifyList(data) {
        var _this = this;

        return _asyncToGenerator(function* () {
            const Op = _this.db.Sequelize.Op;
            data.start = (parseInt(data.page) - 1) * parseInt(data.pageSize);
            let where = {
                del_flag: '0'
            };
            if (data.title) {
                where.title = {
                    [Op.like]: '%' + data.title + '%'
                };
            }
            try {
                return yield _this.oaNotifyModel.findAndCountAll({
                    where: where,
                    limit: parseInt(data.pageSize),
                    offset: parseInt(data.start),
                    order: [['create_date', 'DESC']]
                });
            } catch (error) {
                return _this.exceptionService.handleError(error);
            }
        })();
    }

    userIdOaNotifyList(data) {
        var _this2 = this;

        return _asyncToGenerator(function* () {
            const Op = _this2.db.Sequelize.Op;

            data.start = (parseInt(data.page) - 1) * parseInt(data.pageSize);
            let where = {
                user_id: data.user_id
            };
            if (data.title) {
                where.title = {
                    [Op.like]: '%' + data.title + '%'
                };
            }
            try {
                const result = yield _this2.oaNotifyRecordModel.findAndCountAll({
                    where: where,
                    limit: parseInt(data.pageSize),
                    offset: parseInt(data.start)
                });
                return result;
            } catch (error) {
                return _this2.exceptionService.handleError(error);
            }
        })();
    }

    getNotifyList(data) {
        var _this3 = this;

        return _asyncToGenerator(function* () {
            let start = (parseInt(data.page) - 1) * parseInt(data.pageSize);
            let size = parseInt(data.pageSize);
            console.log('80808080808080808');

            try {
                let sql;
                if (data.title) {
                    sql = `SELECT a.user_id, a.read_flag, b.id, b.type, b.title, b.content, b.files, b.status, b.create_by, 
            b.create_date, b.update_by, b.update_date, b.remarks, c.username FROM oa_notify_record AS a 
            LEFT OUTER JOIN oa_notify AS b ON a.oa_notify_id = b.id 
            LEFT OUTER JOIN sys_user AS c ON c.id = b.create_by 
            WHERE b.del_flag = 0 AND a.user_id = '${data.user_id}' AND b.title LIKE '%${data.title}%'
            ORDER BY b.create_date DESC LIMIT ${start}, ${size}`;
                } else {
                    sql = `SELECT a.user_id, a.read_flag, b.id, b.type, b.title, b.content, b.files, b.status, b.create_by, 
            b.create_date, b.update_by, b.update_date, b.remarks, c.username FROM oa_notify_record AS a 
            LEFT OUTER JOIN oa_notify AS b ON a.oa_notify_id = b.id 
            LEFT OUTER JOIN sys_user AS c ON c.id = b.create_by 
            WHERE b.del_flag = 0 AND a.user_id = '${data.user_id}' 
            ORDER BY b.create_date DESC LIMIT ${start}, ${size}`;
                }
                console.log('999999000000000000', sql);

                return yield _this3.CrudService.querySql(sql);
            } catch (err) {
                return _this3.exceptionService.handleError(err);
            }
        })();
    }

    getNotifyListCount(data) {
        var _this4 = this;

        return _asyncToGenerator(function* () {
            try {
                let sql;
                if (data.title) {
                    sql = `SELECT a.user_id, a.read_flag, b.id, b.type, b.title, b.content, b.files, b.status, b.create_by, 
            b.create_date, b.update_by, b.update_date, b.remarks, c.username FROM oa_notify_record AS a 
            LEFT OUTER JOIN oa_notify AS b ON a.oa_notify_id = b.id 
            LEFT OUTER JOIN sys_user AS c ON c.id = b.create_by 
            WHERE b.del_flag = 0 AND a.user_id = '${data.user_id}' AND b.title LIKE '%${data.title}%'
            ORDER BY b.create_date DESC`;
                } else {
                    sql = `SELECT a.user_id, a.read_flag, b.id, b.type, b.title, b.content, b.files, b.status, b.create_by, 
            b.create_date, b.update_by, b.update_date, b.remarks, c.username FROM oa_notify_record AS a 
            LEFT OUTER JOIN oa_notify AS b ON a.oa_notify_id = b.id 
            LEFT OUTER JOIN sys_user AS c ON c.id = b.create_by 
            WHERE b.del_flag = 0 AND a.user_id = '${data.user_id}' 
            ORDER BY b.create_date DESC`;
                }
                return yield _this4.CrudService.querySql(sql);
            } catch (err) {
                return _this4.exceptionService.handleError(err);
            }
        })();
    }

    getAllNotifyList(data) {
        var _this5 = this;

        return _asyncToGenerator(function* () {
            try {
                const sql = `SELECT a.user_id, a.read_flag, b.id, b.type, b.title, b.content, b.files, b.status, b.create_by, 
            b.create_date, b.update_by, b.update_date, b.remarks, c.username FROM oa_notify_record AS a 
            LEFT OUTER JOIN oa_notify AS b ON a.oa_notify_id = b.id 
            LEFT OUTER JOIN sys_user AS c ON c.id = b.create_by 
            WHERE b.del_flag = 0 AND a.user_id = '${data.user_id}' 
            ORDER BY b.create_date DESC`;

                return yield _this5.CrudService.querySql(sql);
            } catch (err) {
                return _this5.exceptionService.handleError(err);
            }
        })();
    }

    notifyTypes() {
        var _this6 = this;

        return _asyncToGenerator(function* () {
            let where = {
                typegroupcode: 'tzlx'
            };
            try {
                const type_id = yield _this6.type_group_model.findOne({ where: where });
                if (type_id) {
                    let query = {
                        typegroupid: type_id.id
                    };
                    return yield _this6.typeModel.findAll({ where: query });
                }
            } catch (error) {
                return _this6.exceptionService.handleError(error);
            }
        })();
    }

    //获取通知详情
    notifyDetails(data) {
        var _this7 = this;

        return _asyncToGenerator(function* () {
            let where = {
                id: data.id
            };
            let query = {
                businesskey: data.id
            };
            let param = {
                read_flag: 1,
                read_date: new Date()

            };
            let notify_id = {
                oa_notify_id: data.id,
                user_id: data.userId
            };

            try {
                let readed = yield _this7.oaNotifyRecordModel.update(param, { where: notify_id });
                let res = yield _this7.oaNotifyModel.findOne({ where: where });
                let result = yield _this7.attachmentModel.findAll({ where: query });
                if (readed) {
                    console.log('成功');
                }
                let data = {
                    res: res,
                    result: result
                };
                return data;
            } catch (error) {
                return _this7.exceptionService.handleError(error);
            }
        })();
    }

    allUserIdOaNotifyList(data) {
        var _this8 = this;

        return _asyncToGenerator(function* () {

            let where = {
                user_id: data.user_id
            };
            try {
                const result = yield _this8.oaNotifyRecordModel.findAll({
                    where: where
                });
                return result;
            } catch (error) {
                return _this8.exceptionService.handleError(error);
            }
        })();
    }

    notifyIdOaNotifyList(data) {
        var _this9 = this;

        return _asyncToGenerator(function* () {
            const Op = _this9.db.Sequelize.Op;
            data.start = (parseInt(data.page) - 1) * parseInt(data.pageSize);
            let where = {
                oa_notify_id: data.oa_notify_id
            };
            try {
                const result = yield _this9.oaNotifyRecordModel.findAndCountAll({
                    where: where,
                    limit: parseInt(data.pageSize),
                    offset: parseInt(data.start)
                });
                return result;
            } catch (error) {
                return _this9.exceptionService.handleError(error);
            }
        })();
    }

    allNotifyIdOaNotifyList(data) {
        var _this10 = this;

        return _asyncToGenerator(function* () {
            let where = {
                oa_notify_id: data.oa_notify_id
            };
            try {
                const result = yield _this10.oaNotifyRecordModel.findAll({
                    where: where
                });
                return result;
            } catch (error) {
                return _this10.exceptionService.handleError(error);
            }
        })();
    }

    notify(data) {
        var _this11 = this;

        return _asyncToGenerator(function* () {
            const Op = _this11.db.Sequelize.Op;
            let where = {
                id: data.params.oa_notify_id
            };
            if (data.params.title) {
                where.title = {
                    [Op.like]: '%' + data.params.title + '%'
                };
            }
            try {
                return yield _this11.oaNotifyModel.findOne({
                    where: where
                });
            } catch (error) {
                return _this11.exceptionService.handleError(error);
            }
        })();
    }

    //获取用户列表
    getUserList() {
        var _this12 = this;

        return _asyncToGenerator(function* () {
            try {
                return yield _this12.userModel.findAll();
            } catch (error) {
                return _this12.exceptionService.handleError(error);
            }
        })();
    }

    //获取微信用户列表
    getWeChatUserList() {
        var _this13 = this;

        return _asyncToGenerator(function* () {
            try {
                return yield _this13.weChatUserModel.findAll();
            } catch (error) {
                return _this13.exceptionService.handleError(error);
            }
        })();
    }

    //保存文件（多文件)
    saveFile(data) {
        var _this14 = this;

        return _asyncToGenerator(function* () {
            try {
                let params = {
                    id: think.uuid('v1'),
                    user_id: data.id,
                    realpath: data.realpath,
                    create_date: new Date(),
                    businesskey: data.id,
                    file_name: '通知通告'

                };
                return yield _this14.attachmentModel.create(params);
            } catch (error) {
                return _this14.exceptionService.handleError(error);
            }
        })();
    }

    //新增通知
    oaNotifyAdd(data) {
        var _this15 = this;

        return _asyncToGenerator(function* () {

            try {
                data.id = think.uuid('v1');
                let result = yield _this15.oaNotifyModel.create(data);

                if (!result.error) {
                    return yield _this15.oaNotifyModel.findOne({
                        where: {
                            id: data.id
                        }
                    });
                }
            } catch (error) {
                return _this15.exceptionService.handleError(error);
            }
        })();
    }

    // 发送通知
    sendOaNotify(data) {
        var _this16 = this;

        return _asyncToGenerator(function* () {

            if (typeof data.user_id === "string") {
                data.user_id = JSON.parse(data.user_id);
                data.notify = JSON.parse(data.notify);
            }
            try {
                if (data.user_id.length > 0) {
                    let flag;
                    for (let item of data.user_id) {
                        let res = {
                            id: think.uuid('v1'),
                            oa_notify_id: data.notify.id,
                            user_id: item
                        };
                        flag = yield _this16.oaNotifyRecordModel.create(res);
                    }
                    if (!flag.error) {
                        let param = {
                            status: '1'
                        };

                        let updateResult = yield _this16.oaNotifyModel.update(param, {
                            where: {
                                id: data.notify.id
                            }
                        });

                        //向移动端发送通知
                        let axios = require("axios");
                        let url = _this16.pushServerUrl;
                        let pushData = {
                            targets: data.user_id,
                            sender: data.notify.id,
                            title: data.notify.title,
                            type: 12,
                            objectName: 'RC:TxtMsg',
                            content: data.notify.remarks || '',
                            customData: {
                                id: data.notify.id,
                                title: data.notify.title
                            }
                        };
                        let postData = {
                            data: JSON.stringify(pushData)
                        };

                        axios.post(url, postData).then(function (ret) {
                            console.log('111111111');
                        }).catch(function (err) {
                            console.log(err);
                        });

                        return updateResult;
                    }
                }
            } catch (error) {
                return _this16.exceptionService.handleError(error);
            }
        })();
    }

    //发送派遣核实消息
    sendMsgNotify(data) {
        var _this17 = this;

        return _asyncToGenerator(function* () {
            try {
                if (data.user_id.length > 0) {
                    let query = {
                        verify_by: data.user_id,
                        status: 2,
                        update_by: data.msg.sys_id,
                        update_date: new Date()
                    };
                    let where = {
                        id: data.msg.id
                    };

                    let flag = yield _this17.eventModel.update(query, {
                        where: where
                    });
                    let area = {
                        area_code: data.msg.area_code
                    };

                    let areaCode = yield _this17.areaCodeModel.findOne({
                        where: area
                    });
                    let cont = '';
                    if (areaCode && areaCode.area_name) {
                        cont = '[' + data.msg.parent_name + ']' + ' ' + areaCode.area_name + ',' + data.msg.remarks;
                    } else {
                        cont = '[' + data.msg.parent_name + ']' + data.msg.remarks;
                    }

                    if (!flag.error) {
                        let axios = require('axios');
                        let url = _this17.pushServerUrl;
                        let arr = [];
                        arr.push(data.user_id);

                        let pushData = {
                            targets: arr, //目标用户ID数组
                            sender: data.msg.sys_id, //发送者ID，系统消息可以为空
                            title: data.msg.parent_name + ' 待您核实', //手机端通知栏的标题
                            type: 11, //消息类型
                            objectName: 'RC:TxtMsg', //文字类型
                            content: cont, //消息内容（140字符以内）
                            customData: { //自定义业务数据
                                label: 1101, //待审核事件
                                id: data.msg.id, //业务ID – 待办事件ID
                                title: data.msg.parent_name + ' 待您核实',
                                sender_id: data.msg.sys_id,
                                type: 11
                            }
                        };

                        let postData = {
                            data: JSON.stringify(pushData)
                        };

                        axios.post(url, postData).then(function (ret) {
                            console.log('不对吗');
                        }).catch(function (err) {
                            console.log(err);
                        });

                        return flag;
                    }
                }
            } catch (error) {
                return _this17.exceptionService.handleError(error);
            }
        })();
    }

    //删除通知
    delOaNotify(data) {
        var _this18 = this;

        return _asyncToGenerator(function* () {
            try {
                if (data.id) {
                    let where = {
                        id: data.id
                    };
                    let param = {
                        del_flag: '1'
                    };
                    let res = yield _this18.oaNotifyRecordModel.destroy({
                        where: where
                    });
                    if (!res.error) {
                        return yield _this18.oaNotifyModel.update(param, {
                            where: where
                        });
                    }
                }
            } catch (error) {
                return _this18.exceptionService.handleError(error);
            }
        })();
    }

    //修改状态
    updateOaNotify(data) {
        var _this19 = this;

        return _asyncToGenerator(function* () {

            try {
                if (data.id) {
                    let where = {
                        oa_notify_id: data.id,
                        user_id: data.user_id
                    };
                    let param = {
                        read_flag: 1,
                        read_date: new Date()
                    };
                    return yield _this19.oaNotifyRecordModel.update(param, {
                        where: where
                    });
                }
            } catch (error) {
                return _this19.exceptionService.handleError(error);
            }
        })();
    }

    getOrgAndUser(data) {
        var _this20 = this;

        return _asyncToGenerator(function* () {
            try {
                let where = {};
                if (data.org_name) {
                    where = {
                        org_name: {
                            $like: '%' + data.org_name + '%'
                        }
                    };
                }
                const org = yield _this20.orgModel.findAll({
                    where: where,
                    include: [{
                        association: _this20.orgModel.hasMany(_this20.userModel, {
                            foreignKey: 'org_id'
                        }),
                        where: {
                            del_flag: 0
                        },
                        attributes: ['id', 'realname', 'org_id', 'phone'],
                        required: false
                    }],
                    order: [['org_code', 'ASC']]
                });
                let list = [];
                if (org) {
                    if (data.id) {
                        console.log('org存在-----------');
                        console.log(data.id);

                        list = _this20.getChild(org, data.id);
                    } else {
                        list = org;
                    }
                }
                return list;
            } catch (error) {
                return _this20.exceptionService.handleError(error);
            }
        })();
    }

    updateNotifyRecord(data) {
        var _this21 = this;

        return _asyncToGenerator(function* () {
            try {
                if (data.id) {
                    let where = {
                        oa_notify_id: data.id
                    };
                    let param = {
                        read_flag: 1,
                        read_date: new Date()
                    };
                    return yield _this21.oaNotifyRecordModel.update(param, {
                        where: where
                    });
                }
            } catch (error) {
                return _this21.exceptionService.handleError(error);
            }
        })();
    }

    getChild(arr, id) {
        var temp = [];
        let lev = 0;

        for (let item of arr) {
            if (item.id == id) {
                temp.push(item);
            }
        }

        var forFn = function (arr, id, lev) {
            for (let item of arr) {

                if (item.parent_id == id) {
                    item.lev = lev;
                    temp.push(item);
                    forFn(arr, item.id, lev + 1);
                }
            }
        };
        forFn(arr, id, lev);
        return temp;
    }
};